<?php
namespace V1\Controller;
use Think\Controller;
use V1\Logic\CalendarLogic;
use Common\Library\Exception\BadRequest;
class BaseController extends Controller {
    protected $errorCode = array();
    
    protected $day;
    protected $isOpen=false;
    
    public  function _initialize(){
         header('App-Version:'.substr(MODULE_NAME,1));
         //当前日期判断
            //1.休市 显示上一个交易日信息
            //2.交易日 当日00:00-07:00 显示上一个交易日数据 其他时间继续下面流程
        $this->day = date('Y-m-d',NOW_TIME);
        //$this->day = '2015-05-20';
        $curDay00 = strtotime($this->day.' 00:00');
        $curDay70 = strtotime($this->day.' 07:00');

        $this->isOpen = CalendarLogic::isTradeDay($this->day);
        if(empty($this->isOpen) || (NOW_TIME>=$curDay00 && NOW_TIME<=$curDay70)){
            $this->day = CalendarLogic::getPreTradeDay($this->day);
        }
    }
    /**
     * 检查用户token
     * @throws \Api\Library\Exception\BadRequest
     */
    protected function checkUserToken($isCheckUser=true) {
       $user_token = I('user_token','');
       if(empty($user_token)){
            throw new BadRequest("参数异常", 1);
       }
       //判断user_token是否有效 
      $sessionModel = D('UserSession');
      $uid = $sessionModel->checkExpireTime($user_token);
      
      empty($uid) && $this->responseError('-1');
      
      if($isCheckUser){
            $user_status = M('User')->where("id={$uid}")->getField('status');
            $user_status<>1 && $this->responseError('-1'); 
      }

      return array($uid,$user_token);
    }

     /**
     *  内容输出
     * @param string $data
     * @param string $ret http状态
     * @param string $msg
     * @author 王真先  <wzx@matidata.com>
     */
    protected function responseResult($data,$ret=200,$msg="") {
        $result = array("ret" => $ret,"data" => $data,"msg" => $msg);
        $this->ajaxReturn($result);
    }
  
    protected function responseError($errorCode,$ret=200,$msg="") {
        $data = array("code" => $errorCode,"msg" =>$this->errorCode[strtolower(ACTION_NAME)][$errorCode]);
        $result = array("ret" => $ret,"data" => $data,"msg" => $msg);
        $this->ajaxReturn($result);
    }
    protected function page($model,$fields,$where=array(),$order='id desc',$expires=60,$base = array('status'=>1)){
         
        $pageIndex = I('p',1,'intval');
        $pageSize = I('r',10,'intval');
        
        $where = array_merge( $base,$where);
        $model = M($model);
       
        $result =$model->where($where)->field($fields)->cache($expires)->order($order)->page($pageIndex,$pageSize)->select();
      
        empty($result) && $this->responseError(-10);
        
        return $result;
    }
    /**
     * 通用分页列表数据集获取方法
     *
     *  可以通过url参数传递where条件,例如:  index.html?name=asdfasdfasdfddds
     *  可以通过url空值排序字段和方式,例如: index.html?_field=id&_order=asc
     *  可以通过url参数r指定每页数据条数,例如: index.html?r=5
     *
     * @param sting|Model  $model   模型名或模型实例
     * @param array        $where   where查询条件(优先级: $where>$_REQUEST>模型设定)
     * @param array|string $order   排序条件,传入null时使用sql默认排序或模型属性(优先级最高);
     *                              请求参数中如果指定了_order和_field则据此排序(优先级第二);
     *                              否则使用$order参数(如果$order参数,且模型也没有设定过order,则取主键降序);
     *
     * @param array        $base    基本的查询条件
     * @param boolean      $field   单表模型用不到该参数,要用在多表join时为field()方法指定参数
     * @author 王真先  <wzx@matidata.com>
     *
     * @return array|false
     * 返回数据集
     */
    protected function lists ($model,$where=array(),$order='',$base = array('status'=>array('egt',0)),$field=true){
        $options    =   array();
        $REQUEST    =   (array)I('request.');
       
        if(is_string($model)){
            $model  =   M($model);
        }

        $OPT        =   new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);

        $pk         =   $model->getPk();
        if($order===null){
            //order置空
        }else if ( isset($REQUEST['_order']) && isset($REQUEST['_field']) && in_array(strtolower($REQUEST['_order']),array('desc','asc')) ) {
            $options['order'] = '`'.$REQUEST['_field'].'` '.$REQUEST['_order'];
        }elseif( $order==='' && empty($options['order']) && !empty($pk) ){
            $options['order'] = $pk.' desc';
        }elseif($order){
            $options['order'] = $order;
        }
        unset($REQUEST['_order'],$REQUEST['_field']);

        $options['where'] = array_filter(array_merge( (array)$base, /*$REQUEST,*/ (array)$where ),function($val){
            if($val===''||$val===null){
                return false;
            }else{
                return true;
            }
        });
        if( empty($options['where'])){
            unset($options['where']);
        }
        $options      =   array_merge( (array)$OPT->getValue($model), $options );
        $total        =   $model->where($options['where'])->count();

        if( isset($REQUEST['r']) ){
            $listRows = (int)$REQUEST['r'];
        }else{
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 5;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        
        $options['limit'] = $page->firstRow.','.$page->listRows;

        $model->setProperty('options',$options);
      
        $pagelist = array();
        $pagelist['list'] = $model->field($field)->select();
        $pagelist['page'] = $page->getPages();
        return $pagelist;
    }
    
    /**
     * 条目假删除
     * @param string $model 模型名称,供D函数使用的参数
     * @param array  $where 查询时的where()方法的参数
     * @param array  $msg   执行正确和错误的消息 array('success'=>'','error'=>'', 'url'=>'','ajax'=>false)
     *                     url为跳转页面,ajax是否ajax方式(数字则为倒数计时秒数)
     *
     * @author 王真先  <wzx@matidata.com>
     */
    protected function delete ( $model , $where = array() ) {
        $data['status']         =   -1;
        $data['update_time']    =   NOW_TIME;
        return $this->editRow($model,$data, $where);
    }
    protected function find ( $model , $where = array('status'=>0) ) {
        $id    = array_unique((array)I('id',0));
        $id    = is_array($id) ? implode(',',$id) : $id;
        $where = array_merge( array('id' => array('in', $id )) ,(array)$where );

        return  M($model)->where($where)->select();
    }
    protected function save ($model,$data) {
        if(M($model)->create($data)){
              M($model)->add();
              return true;
        }
        return false ;
    }
    /**
     * 对数据表中的单行或多行记录执行修改 GET参数id为数字或逗号分隔的数字
     *
     * @param string $model 模型名称,供M函数使用的参数
     * @param array  $data  修改的数据
     * @param array  $where 查询时的where()方法的参数
     * @param array  $msg   
     *                     
     *
     * @author 王真先  <wzx@matidata.com>
     */
    final protected function editRow ( $model ,$data, $where  ){
        $id    = array_unique((array)I('id',0));
        $id    = is_array($id) ? implode(',',$id) : $id;
        $where = array_merge( array('id' => array('in', $id )) ,(array)$where );
       if( M($model)->where($where)->save($data)!==false ) {
           return true;
        }else{
           return false;
        }
    }
    
}